import React, { useState } from "react"
import { history } from "umi"
import { useLocation, useHistory } from "react-router"
import { Button, Form, Input, Upload, message, Modal, Popconfirm, Spin } from "antd"
import { LoadingOutlined, PlusOutlined, MinusCircleFilled } from "@ant-design/icons"
import { userPopOut } from "@/services/components/treeGroupMemberSearch"
import { IconsultGroupAddinPam, consultGroupAdd } from "@/services/consultationTeam"


import styles from "./newTeam.less"
import "./importNewTeam.less"

// import GroupMemberSearch from "@/components/GroupMemberSearch" // 普通版本组员搜索组件
import TreeGroupMemberSearch from "@/components/treeGroupMemberSearch" // 树形版本版本组员搜索组件

import ConsultationTeamUpload from "../components/upload" // 暂时基于会诊小组的上传


const newTeam: React.FC = () => {

  const [loading, setLoading] = useState<boolean>(false)
  const [imageUrl, setImageUrl] = useState<string>("")

  const [groupLeader, setGroupLeader] = useState<Array<userPopOut>>([]) // 组长
  const [groupMemberList, setgroupMemberList] = useState<Array<userPopOut>>([]) // 组员

  const [groupLogo, setGroupLogo] = useState<string>("")
  const [groupName, setGroupName] = useState<string>("")
  const [leaderId, setLeaderId] = useState<number | any>()
  const [groupUserIds, setGroupUserIds] = useState<number[] | any>([]) // 组员ids
  const [target, setTarget] = useState<string>("")
  const [description, setDescription] = useState<string>("")


  const [form] = Form.useForm()


  const consultGroupAddFn = async () => {
    let pam: IconsultGroupAddinPam = {
      groupLogo,
      groupName,
      leaderId,
      groupUserIds,
      target,
      description
    }
    setLoading(true)
    const [err, res] = await consultGroupAdd(pam)
    setLoading(false)
    if (err) {
      return message.error(err.message)
    }
    message.success(res.message)
    history.push("/consultationTeam")
  }

  const submitEvent = async () => {
    form.validateFields().then(value => {
      consultGroupAddFn()
    }).catch(err => {

    })
  }





  const layout = {
    labelCol: { span: 4 }, // 标签宽
    // wrapperCol: { span: 6 }, // 右侧输入内容宽
  }

  const tailLayout = {
    wrapperCol: { span: 3 },
  }

  const onFinish = (values: any) => {
    console.log(values)
  }



  /** ****搜索组员弹框*******/
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false) // 组员用

  const [isLeaderVisible, setIsLeaderVisible] = useState<boolean>(false) // 组长用


  // 点击添加组长
  const addLeader = () => {
    setIsLeaderVisible(true)
  }


  // 点击添加组员
  const addGroupMember = () => {
    setIsModalVisible(true)
  }

  // 获取组员
  const getGroupMemberList = (arr: Array<userPopOut>) => {
    console.log("选中的组员：", arr)
    setgroupMemberList(arr)

    let isd: number[] = []
    arr.forEach((item: userPopOut) => {
      isd.push(item.id)
    })
    setGroupUserIds(isd)

  }


  // 获取组长
  const getLeader = (arr: Array<userPopOut>) => {
    console.log("选中的组长：", arr)
    setGroupLeader(arr)
    setLeaderId(arr[0].id)
  }

  /**
   * 
   * @param type 1是组长 2是组员
   * @param item userPopOut
   * @param index 索引
   */
  const delUser = (type: number, item: userPopOut, index: number) => {
    // console.log(type, item, index)
    // const [groupLeader, setGroupLeader] = useState<Array<userPopOut>>([]) // 组长
    // const [groupMemberList, setgroupMemberList] = useState<Array<userPopOut>>([]) // 组员
    if (type === 1) {
      groupLeader.splice(index, 1)
      setGroupLeader([])
      setLeaderId(null)
    }
    if (type === 2) {
      groupMemberList.splice(index, 1)
      setgroupMemberList([...groupMemberList])

      if (groupMemberList.length >= 1) {
        let isd: number[] = []
        groupMemberList.forEach((item: userPopOut) => {
          isd.push(item.id)
        })
        setGroupUserIds(isd)
      }


    }

  }

  /** *** end *******/

  const groupNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setGroupName(e.target.value)
  }
  const targetChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setTarget(e.target.value)
  }
  const descriptionChange = (e: any) => {
    setDescription(e.target.value)
  }


  return (
    <div className={styles.newTeamWrap}>
      {loading ? <Spin className="spinClass" tip="加载中..." /> : null}
      <Form {...layout} form={form} onFinish={onFinish} >

        <div className={styles.formContent} >
          <div className={styles.formContentLeft}  >
            <Form.Item name="groupName" label="小组名称" rules={[{ required: true }]}>
              <Input value={groupName} onChange={groupNameChange} placeholder="请输入小组名称" />
            </Form.Item>
            <Form.Item name="target" label="会诊对象" rules={[{ required: true }]}>
              <Input value={target} onChange={targetChange} placeholder="请输入会诊对象" />
            </Form.Item>
            <Form.Item name="description" label="小组简介">
              <Input.TextArea value={description} onChange={descriptionChange} placeholder="请输入小组简介" />
            </Form.Item>
          </div>

          <div className={`${"formContentRight"} ${styles["formContentRight"]}`} >
            <div className={styles.formContentRightTop} >
              <Form.Item label="头像"  >
                <ConsultationTeamUpload getUrl={setGroupLogo} />
              </Form.Item>
              <Form.Item name="leaderId" rules={[
                {
                  required: true,
                  validator: async (_, names) => {
                    if (!leaderId || leaderId === 0 || leaderId === null) {
                      return Promise.reject(new Error("请选择组长"))
                    }
                  },
                }
              ]} label="组长" >

                {
                  groupLeader.map((item: userPopOut, index: number) => {
                    return (
                      <div key={item.id} style={{ width: "unset", paddingTop: 0 }} className={styles.manItem}>
                        <div className={styles.manTop} >
                          <img className={styles.manItemImg} src={item.photo} />
                          <div className={styles.MinusCircleFilledWrap}>

                            <Popconfirm
                              title={`确认要删除组长${item.name}吗？`}
                              okText="确认"
                              cancelText="取消"
                              onConfirm={() => { delUser(1, item, index) }}
                            >
                              <MinusCircleFilled className={styles.smallMinusCircleFilled} />
                            </Popconfirm>

                          </div>
                        </div>
                        <div className={styles.manItemName} >{item.name}</div>
                        <div className={styles.manItemBottom}>{item.jobTitleName}</div>
                      </div>
                    )

                  })
                }


                {
                  groupLeader.length === 0 ?
                    <div style={{ paddingTop: groupLeader.length === 0 ? 0 : "30px", width: "unset" }} className={styles.RightTopPlusOutlinedWrap}>
                      <PlusOutlined onClick={addLeader} className={styles.RightTopPlusOutlined} />
                      <span style={{ position: "absolute", left: "68px", top: "15px", color: "rgba(0, 0, 0, 0.3)" }} >请选择组长</span>
                    </div>
                    : null
                }
              </Form.Item>
            </div>

            <Form.Item name="groupUserIds" className={styles.manScroll} labelCol={{ span: 2 }} rules={[
              {
                required: true,
                validator: async (_, names) => {
                  if (!groupUserIds || groupUserIds.length === 0) {
                    return Promise.reject(new Error("请选择组员"))
                  }
                },
              }
            ]}
              label="组员">

              {
                groupMemberList.map((item: userPopOut, index: number) => {
                  return (
                    <div key={item.id} className={styles.manItem}>
                      <div className={styles.manTop} >
                        <img className={styles.manItemImg} src={item.photo} />
                        <div className={styles.MinusCircleFilledWrap}>
                          <Popconfirm
                            title={`确认要删除组员${item.name}吗？`}
                            okText="确认"
                            cancelText="取消"
                            onConfirm={() => { delUser(2, item, index) }}
                          >
                            <MinusCircleFilled className={styles.smallMinusCircleFilled} />
                          </Popconfirm>
                        </div>
                      </div>
                      <div className={styles.manItemName} >{item.name}</div>
                      <div className={styles.manItemBottom}>{item.jobTitleName}</div>
                    </div>
                  )

                })
              }


              <div style={{ paddingTop: groupMemberList.length === 0 ? 0 : "30px" }} className={styles.RightTopPlusOutlinedWrap} >
                <PlusOutlined onClick={addGroupMember} className={styles.RightTopPlusOutlined} />
              </div>



            </Form.Item>
          </div>
        </div>

      </Form>
      <div style={{ textAlign: "center" }}>
        <Button className={styles.cancel} >
          取消
        </Button>
        <Button className={styles.determine} style={{ marginLeft: "30px" }} type="primary" onClick={submitEvent} >
          确定
        </Button>
      </div>

      {/* 树形控件 版本的 组员专用搜索 */}
      {
        isModalVisible ? <TreeGroupMemberSearch isModalVisible={isModalVisible} setIsModalVisible={setIsModalVisible} getChildParam={getGroupMemberList} /> : null
      }

      {/* 树形控件 版本的 组长专用搜索 */}
      {
        isLeaderVisible ? <TreeGroupMemberSearch isSelectMultiple isModalVisible={isLeaderVisible} setIsModalVisible={setIsLeaderVisible} getChildParam={getLeader} /> : null
      }


    </div >
  )
}

export default newTeam
